<?php
class EWebby_CacheTable {
	public $cacheDirectory;

	private function _getCacheFileName($key) {
		return $this->cacheDirectory . md5($key);
	}
	
	public function get($key) {
		$filename = $this->_getCacheFileName($key);
		if( file_exists($filename) ) {
			$content = file_get_contents($filename);
			if( strlen($content) > 0 ) {
				$cacheTableItem = unserialize($content);
				if( $cacheTableItem instanceof EWebby_CacheTableItem ) {
					if( $cacheTableItem->timeOut == 0
						|| (time() - filemtime($filename)) < $cacheTableItem->timeOut ) {
						return $cacheTableItem->cacheObject;
					} else {
						$this->clear($key);		// clear the cache ( when expired )
					}
				}
			}
		}
		
		return null;
	}
	
	public function save($key, $value, $timeOut=0) {
		$cacheTableItem = new EWebby_CacheTableItem();
		$cacheTableItem->cacheObject = $value;
		$cacheTableItem->timeOut = $timeOut;
		$cacheTableItem->key = $key;
		
		$content = serialize($cacheTableItem);
		$filename = $this->_getCacheFileName($key);
		if( ($fp = fopen($filename, 'w')) != null ) { 
			fwrite($fp, $content);
			fclose($fp);
			
			return true;
		}
		
		return false;
	}
	
	public function contains($key) {
		return file_exists($this->_getCacheFileName($key));
	}
	
	public function clear($key) {
		unlink( $this->_getCacheFileName($key) );
	}
	
	public function clearAll() {
		if( ($d = dir($this->cacheDirectory)) != null ) {
			while( ($entry = $d->read()) != null ) {
				$filename = $this->cacheDirectory . $entry;
				if ($entry != '.' && $entry != '..' && is_file($filename) ) {
					unlink($filename);
				}
			}
			
			$d->close();
		}
	}
}